/*
 * @Author: 方块
 * @Date: 2020-05-21 10:31:55
 * @LastEditTime: 2020-05-25 22:16:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jump\assets\script\game\stage\Block.ts
 */ 

const {ccclass, property} = cc._decorator;

@ccclass
export class Block extends cc.Component {

    @property(cc.Float)
    public maxScale: number = 0;
    @property(cc.Float)
    public minScale: number = 0;
    @property(cc.Float)
    public maxDistance: number = 0;
    @property(cc.Float)
    public minDistance: number = 0;
    @property(cc.Float)
    public anchorOffset: number = 0;
    @property(cc.Integer)
    public score: number = 1;

    @property([cc.Node])
    private rightAnchorList: Array<cc.Node> = [];
    @property([cc.Node])
    private leftAnchorList: Array<cc.Node> = [];
    @property(cc.Node)
    private centerAnchor: cc.Node = null;

    @property(cc.Node)
    private p1: cc.Node = null;
    @property(cc.Node)
    private p2: cc.Node = null;

    // 一个小方块分为 ---> 上下中左右 五小块
    // 获取小方块 中小块的世界坐标
    public getCenterPosition():cc.Vec2 {
        // 中小块 代表的是整个方块平面的 中心位置 ---> 转为世界坐标 返回  这样就获得了 方块平面的中心位置
        return this.centerAnchor.parent.convertToWorldSpaceAR(cc.v2(this.centerAnchor.x, this.centerAnchor.y));
    }

    public getAnchorLocation(worldPos: cc.Vec2, direction: number): cc.Vec2 {
        let localPos = this.node.convertToNodeSpaceAR(worldPos);
        // 落点位置
        let anchorList = direction > 0 ? this.rightAnchorList : this.leftAnchorList;
        // 最近的锚点
        let nearAnchor = anchorList[0];
        for (let i = 1; i < anchorList.length; i++) {
            // 寻找 目标位置 与 方块哪个锚点离的最近
            let distance = cc.v2(anchorList[i].x, anchorList[i].y).sub(localPos).mag();
            let distance2 = cc.v2(nearAnchor.x, nearAnchor.y).sub(localPos).mag();
            if (distance < distance2) {
                nearAnchor = anchorList[i];
            }
        }

        // 如果 目标位置与方块离的最近的锚点的距离 小于误差范围，那么就认为是跳跃成功，
        // 返回这个锚点的位置，让玩家直接移动到这个锚点位置
        if(cc.v2(nearAnchor.x, nearAnchor.y).sub(localPos).mag() <= this.anchorOffset) {
            return nearAnchor.parent.convertToWorldSpaceAR(cc.v2(nearAnchor.x, nearAnchor.y));
        } else {
            return null;
        }
    }

    // 得分动画
    public playScoreAnim() {
        cc.find("score", this.node).getComponent(cc.Label).string = "+" + this.score;
        cc.find("score", this.node).getComponent(cc.Animation).play();
    }
}